package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreDateUtils;
import com.lehecai.core.util.CoreFetcherUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableTag;
import org.htmlparser.tags.TableRow;
import org.htmlparser.util.NodeList;

/**
 * 上海11选5 官方开奖结果抓取
 * 地址: http://caipiao.gooooal.com/bonussh115!query.action
 * @author He Wang
 *
 */
public class LotteryDrawFetch562WorkerOfficial extends AbstractLotteryDrawFetchWorker {

    private final static String URL_HISTORY = "http://caipiao.gooooal.com/bonussh115!query.action";

	public LotteryDrawFetch562WorkerOfficial() {
		super(LotteryType.SH11X5);
	}
	
	@Override
	public LotteryDraw fetchResultDetail(String phase) {
        LotteryType lotteryType = this.getLotteryType();

        String fetchUrl = this.getResultDetailUrl(phase);
        if (StringUtils.isEmpty(fetchUrl)) {
            logger.error("==详细页面==抓取=={}==期号：{}==详细地址不存在，返回null", lotteryType.getName(), phase);
            return null;
        }

        String data = null;
        String encoding = "utf-8";

        try {
            data = CoreFetcherUtils.URLGet(fetchUrl, null, encoding);
        } catch (Exception e) {
            logger.error("获取html数据失败" + e.getMessage());
            return null;
        }

        Parser parser;
        try {
            parser = Parser.createParser(data, CharsetConstant.CHARSET_UTF8);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("解析html出错, data={}", data);
            return null;
        }

        // 找到开奖号码所在的table
        NodeList drawRowNodeList = null;
        LotteryDraw lotteryDraw = null;
        try {
            NodeFilter tableFilter = new TagNameFilter("table");
            drawRowNodeList = parser.extractAllNodesThatMatch(tableFilter);
            if (drawRowNodeList == null) {
                logger.error("未找到开奖号码所在的数据区, data={}", data);
                return null;
            }
            if (drawRowNodeList.size() != 1) {
                logger.error("开奖号码所在的数据区出现变化, data={}", data);
                return null;
            }
            TableTag tableTag = (TableTag)drawRowNodeList.elementAt(0);
            for (int i = 1; i < tableTag.getRowCount(); i++) {
                TableRow tableRow = tableTag.getRow(i);
                TableColumn[] columnArray = tableRow.getColumns();
                String tempPhase = columnArray[0].getStringText().trim();
                String tempResult = columnArray[1].getChildrenHTML();
                String tempDrawTime = CoreDateUtils.formatDateTime(CoreDateUtils.parseDate(columnArray[2].getChildrenHTML(), "yyyy-MM-dd HH:mm"));
                tempResult = StringUtils.split(tempResult, "'")[1];
                if (StringUtils.isEmpty(phase)) {
                    lotteryDraw = new LotteryDraw();
                    lotteryDraw.setLotteryType(lotteryType);
                    lotteryDraw.setPhase(tempPhase);
                    lotteryDraw.setResult(tempResult);
                    lotteryDraw.setTimeDraw(tempDrawTime);
                    break;
                } else {
                    if (tempPhase.equals(phase)) {
                        lotteryDraw = new LotteryDraw();
                        lotteryDraw.setLotteryType(lotteryType);
                        lotteryDraw.setPhase(tempPhase);
                        lotteryDraw.setResult(tempResult);
                        lotteryDraw.setTimeDraw(tempDrawTime);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }

        if (lotteryDraw == null || lotteryDraw.getPhase() == null) {
            logger.error("未抓取到彩期数据或彩期不匹配");
            return null;
        }

        return lotteryDraw;
	}

	@Override
	public LotteryDraw fetchResult(String phase) {
		return this.fetchResultDetail(phase);
	}

	@Override
	protected String getResultDetailUrl(String phase) {
        if (StringUtils.isEmpty(phase)) {
            return URL_HISTORY;
        }
        if (phase.length() == 10) {
            String dateStr = CoreDateUtils.formatDate(CoreDateUtils.parseDate(phase.substring(0, 8), "yyyyMMdd"));
            return URL_HISTORY + "?date=" + dateStr;
        }
		return null;
	}

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}
}
